package com.xls.box2023.wxshare;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.lzz.bottomencapsulation.BuildConfig;
import com.lzz.bottomencapsulation.statusbar.StatusBarHeightView;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.TUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xls.box2023.R;
import com.xls.box2023.customcontrol.RoundedImageView;
import com.xls.box2023.entity.UserEntity;
import com.xls.box2023.mvp.MVPBaseActivity;
import com.xls.box2023.utils.SPUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * MVPPlugin
 */

public class WXShareActivity extends MVPBaseActivity<WXShareContract.View, WXSharePresenter> implements WXShareContract.View, View.OnClickListener {

    private TextView title_text;
    private TextView title_back;
    private RelativeLayout title_rl;
    private StatusBarHeightView title_rl_content;
    private TextView share_btn;
    private ImageView share_code;
    private RoundedImageView home_head;

    private TextView home_nicename;

    private RelativeLayout rl_bitmap;

    private RelativeLayout Rl_code;
    private ImageView logo;

    public static void start(Activity activity) {
        Intent intent=new Intent(activity,WXShareActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getView() {
        return R.layout.acttivity_share;
    }
    Bitmap bitmap;
    @Override
    public void initView() {
        title_text = findViewById(R.id.title_text);
        title_back = findViewById(R.id.title_back);
        title_rl = findViewById(R.id.title_rl);
        logo=findViewById(R.id.logo);
        title_rl_content = findViewById(R.id.title_rl_content);
        home_nicename=findViewById(R.id.home_nicename);
        home_head=findViewById(R.id.home_head);
        share_btn = findViewById(R.id.share_btn);
        share_code = findViewById(R.id.share_code);
        share_code.setImageBitmap(AppUtils.getBitmap(this));
        Rl_code=findViewById(R.id.Rl_code);
        rl_bitmap=findViewById(R.id.rl_bitmap);
        title_back.setOnClickListener(this);
        share_btn.setOnClickListener(this);
        title_text.setText("分享二维码");
       UserEntity requestData= SPUtils.getUserInfo();
       if (requestData!=null){
           DisplayImageOptions options = new DisplayImageOptions.Builder()
                   .cacheInMemory(false)// 设置下载的图片是否缓存在内存中
                   .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                   .build();
           ImageLoader.getInstance().displayImage(requestData.getAvatar(),home_head, options);
           if (!TextUtils.isEmpty(requestData.getNickname()))  home_nicename.setText(requestData.getNickname());
       }

    }

    public Bitmap qrcode(String content){
        int width = 413;
        int height = 413;
//    HashMap设置二维码参数
        Map map = new HashMap();
//       设置容错率 L>M>Q>H  等级越高扫描时间越长,准确率越高
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//         设置字符集
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
//         设置外边距
        map.put(EncodeHintType.MARGIN,1);
//         利用编码器，生成二维码
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        Bitmap bitmap = null;
        try {
            bitmap = barcodeEncoder.encodeBitmap(content, BarcodeFormat.QR_CODE, width, height,map);
        }
        catch (WriterException e) {
            e.printStackTrace();}return  bitmap;
    }

    //给二维码添加图片
    //第一个参数为原二维码，第二个参数为添加的logo
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        //如果原二维码为空，返回空
        if (src ==null ) {
            return null;
        }
        //如果logo为空，返回原二维码
        if (src ==null ||logo ==null) {
            return src;
        }

        //这里得到原二维码bitmap的数据
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        //logo的Width和Height
        int logoWidth = 40;
        int logoHeight =40;

        //同样如果为空，返回空
        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }


        //logo大小为二维码整体大小的1/5，也可以自定义多大，越小越好
        //二维码有一定的纠错功能，中间图片越小，越容易纠错
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2,null );

            canvas.save();
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_back) {
            finish();
        } else if (id == R.id.share_btn) {
            share();
        }
    }

    /**
     * 分享
     */
    private void share() {
        if (!WxShareUtils.getInstance().isWeixinAvilible(this)){
            TUtils.showShort(this,"请安装微信");
            return;
        }
        if (bitmap==null)return;
        WxShareUtils.getInstance().shareBitmap(this, BuildConfig.WX_APP_ID, mPresenter.getCacheBitmapFromView(rl_bitmap),"123", SPUtils.getOpenId());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap!=null)bitmap.recycle();
    }

    @Override
    public void showBitmapCode(String wxcodeHost,String unid) {
//        链接需要base64编码  否则前段页面下载时会报错
        bitmap=qrcode(wxcodeHost);
//        bitmap=addLogo(bitmap,AppUtils.getBitmap(this));
        share_code.setImageBitmap(bitmap);
        logo.setImageBitmap(AppUtils.getBitmap(this));
    }


    public static Bitmap imageScaleMin(Bitmap bitmap, int dst_w, int dst_h) {
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();
        float scale_w = ((float) dst_w) / src_w;
        float scale_h = ((float) dst_h) / src_h;

        float min = Math.min(scale_h, scale_w);
//        最大边需要增加的倍数到屏幕边缘，从而达到长宽放大相同倍数，图片不会被压缩，
        Matrix matrix = new Matrix();
        matrix.postScale(min, min);
        Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,true);

        return dstbmp;
    }
}
